#include "devicemonitor.h"

DeviceMonitor::DeviceMonitor()
{
    qDebug() << "deviceMonitor init";
    initDeviceMonitor();
    initScreenInfo();
}

DeviceMonitor::~DeviceMonitor()
{
}

void DeviceMonitor::initScreenInfo()
{
    screenInfo = std::make_unique<ScreenList>();
    for (auto &output : m_config->outputs())
    {
        if (!output.data()->isConnected())
        {
            continue;
        }
        qDebug() << "name :" << output.data()->name() << "id :" << output.data()->id() << "is primary :" << output.data()->isPrimary();
    }
}

void DeviceMonitor::initDeviceMonitor()
{
    getConfigPtr();
    connectSignals();
}

void DeviceMonitor::connectSignals()
{
    if (m_config.data() == nullptr)
    {
        qDebug() << "error :" << __FUNCTION__ << " : " << __LINE__;
        return;
    }

    connect(m_config.data(), &KScreen::Config::outputAdded,
            this, [this](const KScreen::OutputPtr &output)
            { qDebug() << "outputAdded!"; });

    connect(m_config.data(), &KScreen::Config::outputRemoved,
            this, [this](int id)
            { qDebug() << "outputRemoved"; });

    for (const KScreen::OutputPtr &output : m_config->outputs())
    {
        connect(output.data(), &KScreen::Output::isConnectedChanged, this, [output, this]()
                { 
                    qDebug() << "isConnectedChanged" << output.data()->name(); 
                    if (output.data()->isConnected() == true){
                        screenInfo->addDevice(output.data()->id());
                    } else {
                        screenInfo->removeDevice(output.data()->id());
                    } });
    }
}

void DeviceMonitor::getConfigPtr()
{
    op = new KScreen::GetConfigOperation;
    if (!op->exec())
    {
        qDebug() << "error :" << __FUNCTION__ << " : " << __LINE__ << "error " << op->errorString();
        m_config = KScreen::ConfigPtr();
        KScreen::ConfigMonitor::instance()->addConfig(m_config);
        return;
    }

    m_config = op->config();
    KScreen::ConfigMonitor::instance()->addConfig(m_config);
}